from flask_restful import Resource, reqparse, marshal_with

from apps.cinemas.fields import result
from apps.cinemas.helper import concert_district
from apps.cinemas.models import Cinema, HallSchedule, Seat, Hall
from apps.common.result import Result
from apps.main.models import Movies

"""
数据结构:

"""

class CinemaListApi(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('city', type=str,required=True)
        self.parser.add_argument('page', type=int,default=1)
        self.parser.add_argument('size', type=int,default=10)
        self.parser.add_argument('district',type=str)
        # 升序1,降序0
        self.parser.add_argument('order_id', type=int, default=0)
        self.parser.add_argument('order_score', type=int, default=0)

    @marshal_with(result)
    def get(self):
        # 字典类型
        args = self.parser.parse_args()
        city = args.get('city')
        page = args.get('page')
        size = args.get('size')
        district = args.get('district')
        order_id =args.get('order_id')
        order_score = args.get('order_score')

        # distinct去重,城市区县的所有字段,其数据结构[(a,),(),()]
        districts = Cinema.query.with_entities(Cinema.district).filter(Cinema.city == city).distinct(
            Cinema.district).all()

        """综合选择以及排序"""
        query = Cinema.query
        # 选择
        if district:
            query = query.filter(Cinema.district == district)
        # 排序
        if order_id:
            query = query.order_by(Cinema.cid.desc())
        if order_score:
            query = query.order_by(Cinema.score.desc())

        # 分页
        cinemas = query.paginate(page=page,per_page=size,error_out=False).items

        data = {
            'districts': concert_district(districts),
            'cinemas': cinemas
        }

        return Result.get_success_result_obj(data)


class CinemaDetailApi(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('cinema_id', type=int, required=True)

    def get(self):
        cinema_id = self.parser.args('cinema_id')
        # 拿到该影院内排片所有的信息
        schedules = HallSchedule.query.filter(HallSchedule.cid == cinema_id).all()
        movies = []
        for schedule in schedules:
            movie = Movies.query.get(schedule.mid)
            movies.append(movie)
